//
//  OCSSMainTabBarPage.swift
//  OCSSStoreSwift
//
//  Created by MacMiniKangChe on 2018/10/11.
//  Copyright © 2018年 MacMiniKangChe. All rights reserved.
//

import UIKit

class OCSSMainTabBarPage: UITabBarController,UITabBarControllerDelegate {

    var indexFlag = 0;
    
    override func viewDidLoad() {
        super.viewDidLoad()

        initControllers();
    }
    func initControllers() -> Void {
        let filePath = Bundle.main.path(forResource: "TabBarInfo.plist", ofType: nil);
        let tabData:[NSDictionary] = NSArray.init(contentsOfFile: filePath!) as! [NSDictionary];
        for dict in tabData {
            self.addChildViewController(tabInfo: dict);
        }
        
    }
    //Mark:tabbarController添加子视图
    func addChildViewController(tabInfo:NSDictionary) -> Void {
        guard let clsName = Bundle.main.infoDictionary!["CFBundleExecutable"] else {
            return;
        }
        let cls:AnyClass? = NSClassFromString((clsName as! String) + "." + (tabInfo["className"] as! String))
        guard let clsType = cls as? UIViewController.Type else {
            return;
        }
        let childController = clsType.init();
        childController.title = tabInfo["title"] as? String
        childController.tabBarItem.image = UIImage.init(named: tabInfo["normalImage"] as! String)
        childController.tabBarItem.selectedImage = UIImage(named: tabInfo["selectImage"] as! String)
        let nav = UINavigationController.init(rootViewController: childController)
        
        self.addChildViewController(nav)
        
    }
    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        let index = self.tabBar.items!.index(of:item);
        if index != self.indexFlag {
            let array = NSMutableArray.init();
            for btn in self.tabBar.subviews {
                if btn.className() == "UITabBarButton" {
                    array.add(btn);
                }
            }
            tabBarButtonAnimation(array: array as! [UIView], index: index!);
            self.indexFlag = index!;
        }
    }
    func tabBarButtonAnimation(array:[UIView], index:NSInteger) -> Void {
        let animation = CABasicAnimation.init(keyPath: "transform.scale");
        animation.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseOut);
        animation.duration = 0.2;
        animation.repeatCount = 1;
        animation.autoreverses = true;
        animation.fromValue = NSNumber.init(value: 0.7);
        animation.toValue = NSNumber.init(value: 1.3);
        let btn = array[index];
        btn.layer.add(animation, forKey: nil);
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}
